<template>
    <div class="register">
        <div class="container">
            <van-form ref="regForm" @submit="onSubmit" validate-trigger="onChange" validate-first>
                <van-cell-group inset>
                    <van-field v-model="tel" type="tel" name="tel" label="手机号" placeholder="手机号"
                        :rules="[{ required: true, message: '请填写手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }, { validator: validateTel }]" />
                    <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                        :rules="[{ required: true, message: '请填写密码' }]" />
                    <van-field v-model="code" center clearable name="code" label="短信验证码" placeholder="请输入短信验证码"
                        :rules="[{ validator: validateCode }]">
                        <template #button>
                            <van-button class="sendCodeBtn" :disabled="isSend" @click="sendCode(tel)" size="small"
                                type="primary">{{ isSend ?
                                    countDown : '发送验证码' }}</van-button>
                        </template>
                    </van-field>
                </van-cell-group>

                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        提交
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<script setup lang="ts">
//  从声明文件中 引入 对应的类型
import type { Ref } from "vue"
import type { FormInstance } from 'vant';

import { ref } from 'vue';
import { doCheckPhoneAPI, doSendMsgCodeAPI, doCheckCodeAPI, doFinishRegisterAPI } from "@/api/user"
import { useRouter } from "vue-router";

// vantui中的函数组件 => 手动引入
import { showToast } from 'vant';

const tel: Ref = ref<string>('');
const password: Ref = ref<string>('');
const code: Ref = ref<string>('');
const regForm = ref<FormInstance>();

const timer = ref<number | null>(null);
const countDown = ref<number>(60);
const isSend = ref<boolean>(false);

const router = useRouter();

const validateTel = async (tel: number): Promise<any> => {
    console.log("tel", tel);
    try {
        let res = await doCheckPhoneAPI({ tel: tel })
        // console.log("res", res);
        // showToast("可以使用的手机号");
        return true;   //验证成功 => 返回true
    } catch (err: any) {
        showToast(err.message);
        return err.message;  // 验证失败 => 返回false|字符串(错误提示)
    }
}

const sendCode = async (tel: number): Promise<any> => {
    console.log("tel", tel);

    // 1. 发送验证码前 先判断手机号是否可以使用
    // regForm  => ref对象    .value=>表单组件 
    try {
        await (regForm as Ref).value.validate("tel");
        let res = await doSendMsgCodeAPI({ tel: tel });
        showToast("验证码已发送");
        console.log("res", res);

        isSend.value = true;
        timer.value = setInterval(() => {
            countDown.value--;
            if (countDown.value == 0) {
                clearInterval((timer as Ref).value);
            }
        }, 1000)




    } catch (err: any) {
        console.log("err", err);
        showToast(err.message);
    }

}


const validateCode = async (code: string): Promise<any> => {
    console.log("code", code);
    if (!code) return false;

    try {
        let res = await doCheckCodeAPI({
            tel: tel.value,  // tel => ref对象
            telcode: code
        })
        // console.log("res", res);
        // showToast("验证成功");
        return true;   //验证成功 => 返回true
    } catch (err: any) {
        showToast(err.message);
        return false;  // 验证失败 => 返回false|字符串(错误提示)
    }


}

// 全都验证成功才执行  =>
const onSubmit = async (values: any): Promise<any> => {
    console.log('submit', values); // 三个值 {tel,password,code}
    try {
        let res = await doFinishRegisterAPI({
            tel: tel.value,  // tel => ref对象
            password: password.value
        })

        router.push("/login");

    } catch (err: any) {
        showToast(err.message);
        return false;  // 验证失败 => 返回false|字符串(错误提示)
    }

};
</script>

<style scoped>
.register {
    width: 100%;
    height: 100%;
    background-color: #f7f8fa;
    overflow: hidden;
}

.container {
    width: 90%;
    margin: 0 auto;
    margin-top: 1rem;


}

.sendCodeBtn {
    width: 1.64rem;
}
</style>